package com.hxw.es.repository;

import com.hxw.es.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkProcessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class StudentRepository {

    @Autowired
    private BulkProcessor bulkProcessor;

    @Autowired
    private TransportClient transportClient;

    private ObjectMapper objectMapper = new ObjectMapper();
    public void insertBulk (List<Student> studentList){
        if(!studentList.isEmpty()){
            for(Student student:studentList) {
                String id = student.getId()+"";
                try {
                    byte[] json = objectMapper.writeValueAsBytes(student);
                    bulkProcessor.add(new IndexRequest("students", "typeone", id)
                            .source(json, XContentType.JSON));
                } catch (Exception e) {
                    log.error("bulkProcessor failed ,reason:{}", e);
                }
            }
        }

    }

    public void getAllStudent(){
        GetRequestBuilder getRequestBuilder = transportClient.prepareGet("students","typeone","张三5");
        GetResponse getReponse = getRequestBuilder.get();
        String result = getReponse.getSourceAsString();
        System.out.println("result = " + result);
    }

}
